import { crtChannel } from "./crtChannel";
import { crtChannelWeb } from "./crtChannelWeb";
import crtkc from "./crtkc";


/**如花的奇葩事 */
export class crtChannelKs extends crtChannelWeb {
    channelObj: any = (window as any).ks;
    paraMap: Map<String, string> = new Map([
        ['appId', 'ks711005794688986324'],
        ['vedioAd', '2300015622_01'],
        ['insertAd', '2300015622_02'],
        ['bannerAd', '2300015622_03'],
        ['ctrlId', '676cd15fac07a817fa283c64'], //策略开头id
        ['gid', ''], //gid
    ]);


    ruanzhu: string = '著作权人：南京天豆互动网络科技有限公司\n登记号：2022SR0554085';

    /** getSystemInfoSync */
    getSysInfo(): any {
        if (!this.sysInfo) {
            this.sysInfo = this.channelObj.getSystemInfoSync();
        }
        return this.sysInfo;
    }
    init() {
        const me = this;
        const ctrlId = me.getPara('ctrlId');
        if (ctrlId) {
            let sid = crtkc.getData('sid', null);
            if (!sid) {
                try {
                    sid = me.channelObj.getLaunchOptionsSync().from;
                }
                catch {
                    console.error("crtChannelKS")
                }
                if (sid == 'game_center' || sid == 'search') {
                    crtkc.saveData('sid', sid);
                }

            }
            console.error("请求数据: jpost ");
            const reqData = { 'id': ctrlId, sid };
            crtChannel.jpost('https://ga.gametdd.com/adCtrl/agd/conf', reqData, (err, re) => {
                if (err) {
                    console.error("错误: ", err);
                    return;
                }
                if ('' + re.code !== '0') {
                    console.error('返回值错误:' + JSON.stringify(re));
                    return;
                }
                me.ctrl = re.data;
                //@ts-ignore
                window.countTime = me.ctrl['p5'];
                //@ts-ignore
                window.countDown = 2;
                console.error('====>返回', me.ctrl);
            });
        }

        this.ksCheckShow();

    }

    /**快手相关功能 */
    ksCheckShow() {


        console.error('快手onshow');
        const ks = this.channelObj;
        let onShowCallback = (result) => {
            console.error("onshow Result: ", result);
        };
        ks.onShow(onShowCallback);
        // ks.onShow((res) => {
        console.error("onShow onShow: ");
        if (ks.checkSliderBarIsAvailable) {
            ks.checkSliderBarIsAvailable({
                success: (result) => {
                    crtkc.saveData('slideCanUse', 1);
                    console.error("侧边栏调用成功: ", JSON.stringify(result));
                },
                fail: (result) => {
                    crtkc.saveData('slideCanUse', 0);
                    console.error("侧边栏调用失败fail: ", JSON.stringify(result));
                },
            })
        } else {
            console.error("侧边栏调用失败noe exit: ");
            crtkc.saveData('slideCanUse', 0);
        }

        //判断是从哪里进入游戏
        let from = ks.getLaunchOptionsSync().from;
        //侧边栏canGet: 0代表不是从侧边栏进入 1:代表从侧边栏进入
        let hasGet = crtkc.getData('sidebar', { today: '', canGet: '0' });
        let date = new Date();
        let today = date.getUTCFullYear() + "-" + date.getUTCMonth() + "-" + date.getUTCDay();
        if (today != hasGet.today) {
            hasGet.canGet = 0;
        }
        if (from == 'sidebar_miniprogram' || from == 'sidebar_new') {
            hasGet.canGet = 1;
        }
        crtkc.saveData('sidebar', hasGet);

        //桌面快捷方式相关
        if (ks.checkShortcut) {
            ks.checkShortcut({
                success(res) {
                    //根据res.installed 来判断是否添加成功  
                    console.log("是否已添加快捷方式", res.installed);
                    if (res.installed) {//已添加桌面快捷方式
                        crtkc.saveData('shortcutCanUse', 2);
                    } else {
                        crtkc.saveData('shortcutCanUse', 1);
                    }
                },
                fail(err) {
                    if (err.code === -10005) {
                        console.log("暂不支持该功能");
                        crtkc.saveData('shortcutCanUse', 0);
                    } else {
                        console.log("检查快捷方式失败", err.msg);
                        crtkc.saveData('shortcutCanUse', 1);
                    }
                },
                //注意：快捷方式和mini apk的方式，用户装了哪种都算成功走success回调。
                //但是如果都没装的情况下，为兼容以前版本，会先判断快捷方式，再判断mini apk的方式，这种情况最后会走到fail回调
                //所以当err.msg为"apk info is invalid"的情况出现时，也可以在游戏内展示添加桌面的icon提醒用户。
            });
        } else {
            crtkc.saveData('shortcutCanUse', 0);
        }

        //桌面快捷方式 canGet: 0代表不是从桌面快捷方式进入  1代表从桌面快捷方式进入..
        let deskHasGet = crtkc.getData('desk', { today: '', canGet: '0' });
        if (today != deskHasGet.today) {
            deskHasGet.canGet = 0;
        }
        //判断是否从桌面快捷方式进入游戏
        if (ks.isLaunchFromShortcut()) {
            // 表明游戏从手机桌面快捷方式启动  
            deskHasGet.canGet = 1;
        } else {
            // 表明游戏不是从手机桌面快捷方式启动  
        }
        crtkc.saveData('desk', deskHasGet);
        // });

    }

    /**添加桌面快捷方式 */
    addShortCut(paras: { sucCall: any, failCall: any }) {
        const ks = this.channelObj;
        ks.addShortcut({
            success() {
                console.log("添加桌面成功");
                paras.sucCall && paras.sucCall();
            },
            fail(err) {
                if (err.code === -10005) {
                    console.log("暂不支持该功能");
                } else {
                    console.log("添加桌面失败", err.msg);
                }
                paras.failCall && paras.failCall();
            },
        });

    }

    /**添加为常用 */
    addCommonUse(paras: { sucCall: any, failCall: any }) {
        const ks = this.channelObj;
        ks.addCommonUse({
            success() {
                console.log("接口设为常用成功");
                paras.sucCall && paras.sucCall();
            },
            fail(err) {
                if (err.code === -10005) {
                    console.log("暂不支持该功能");
                    paras.failCall && paras.failCall();
                } else {
                    console.log("设为常用失败", err.msg);
                    paras.failCall && paras.failCall();
                }
            },
        });

    }



    /** 分渠道的广告特定动作，actId区分哪个动作,para为执行动作需要的对象
     * 1:点击开始游戏, 恋爱的如花 如花与石头弹出视频广告
     * 
     * 
     */

    doAction(actId: number, para: any) {
        let watchAd = () => {
            this.showVideo(() => {

            });
        }
        if (para && para[0] == 'ks') {
            if (actId == 1) {
                let isOpen = this.getCtrl('p1');
                if (isOpen) {
                    watchAd();
                }
            } else if (actId == 2) {
                let isOpen = this.getCtrl('p2');
                if (isOpen) {
                    this.showVideo(() => {
                        para[1] && para[1]();
                    });
                } else {
                    para[1] && para[1]();
                }
            } else if (actId == 3) {
                let isOpen = this.getCtrl('p3');
                if (isOpen) {
                    watchAd();
                }
            } else if (actId == 4) {
                // let isOpen = this.getCtrl('p4');
                // if(isOpen){
                //     watchAd();
                //     // this.showInter();
                // }
            } else if (actId == 5) {
                watchAd();
            }

        }
    }

    bannerAd: any = null;
    showBanner(isForce?: boolean, styleFn?: any, where?: string): void {
        const id = this.getPara('bannerAd');
        if (!id) {
            return;
        }
        crtkc.log('showBanner isShow', id, where);
        if (this.bannerAd) {
            return;
        }
        const ks = this.channelObj;
        const conf = {
            'adUnitId': id,
            adIntervals: 30,
            style: {
                left: 0,
                top: this.getSysInfo().windowHeight / 2,
                width: 200,
                height: 200
            },
        }
        this.bannerAd = ks.createBannerAd(conf);
        this.bannerAd.onError(err => {
            crtkc.log('banner广告加载失败' + JSON.stringify(err));
            this.bannerAd = null;
        });

        this.bannerAd.onResize((size) => {
            console.log("banner onResize===", size.height, size.width);
            const style = (styleFn) ? styleFn(size) : { top: this.getSysInfo().windowHeight - size.height, left: (this.getSysInfo().windowWidth - size.width) / 2 };
            this.bannerAd.style.top = style.top;
            this.bannerAd.style.left = style.left;
            if (style.height) {
                this.bannerAd.style.height = style.height;
            }
            crtkc.log('bannerAd style:', this.bannerAd.style.top, this.bannerAd.style.left, this.bannerAd.style.height);
        });

        this.bannerAd.show().then(() => {
            crtkc.log('banner显示成功');
        }).catch(err => {
            this.bannerAd = null;
            crtkc.log('showBanner err:' + JSON.stringify(err));
        });
    }

    rewardedVideoAd: any = null;
    /** 用于存放各个回调方法，便于off，如onLoad,onError等 */
    videoFns = {};

    showVideo(succ): void {
        const id = this.getPara('vedioAd');
        console.error('ks showVideo');
        if (!id) {
            return;
        }

        cc.game.pause();
        this.rewardedVideoAd = this.channelObj.createRewardedVideoAd({
            adUnitId: id
        });
        if (this.videoFns['onLoad']) {
            this.rewardedVideoAd.offLoad(this.videoFns['onLoad']);
        }
        if (this.videoFns['onError']) {
            this.rewardedVideoAd.offError(this.videoFns['onError']);
        }
        if (this.videoFns['onClose']) {
            this.rewardedVideoAd.offClose(this.videoFns['onClose']);
        }
        this.rewardedVideoAd.offLoad();
        this.rewardedVideoAd.offError();
        this.rewardedVideoAd.offClose();
        const me = this;
        me.videoFns['onLoad'] = () => {
            crtkc.log('激励视频 广告加载成功');
        };
        me.videoFns['onError'] = (err) => {
            crtkc.err(err);
            cc.game.resume();
            // 视频失败切换分享
            this.channelObj.showToast({
                title: '暂无广告',
            });
        }
        me.videoFns['onClose'] = (res) => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            cc.game.resume();
            if (res && res.isEnded) {
                // 正常播放结束，可以下发游戏奖励
                succ && succ();
            } else {
            }
        };
        me.rewardedVideoAd.onLoad(me.videoFns['onLoad']);
        me.rewardedVideoAd.onError(me.videoFns['onError']);
        me.rewardedVideoAd.onClose(me.videoFns['onClose']);

        me.rewardedVideoAd.show()
            .then(() => {

            }).catch(err => {
                me.rewardedVideoAd.load().then(() => {
                    // 加载成功后需要再显示广告
                    return me.rewardedVideoAd.show().then(() => {

                    }).catch((err) => {
                        cc.game.resume();
                    });
                }).catch((err) => {
                    cc.game.resume();
                });
            });

    }
    /** 插屏间隔秒数 */
    interGap: number = 30 * 1000;
    /** 下次可出插屏的时间 */
    nextInterTime: number = 0;

    doShowInter(isForce?: boolean, style?: any): void {
        const id = this.getPara('insertAd');
        if (!id) {
            return;
        }
        console.error("doShowInter: ", this.nextInterTime, Date.now());
        if (this.nextInterTime > Date.now()) {
            crtkc.err('插屏时间间隔未到');
            return;
        }
        let interstitialAd = this.channelObj.createInterstitialAd({
            adUnitId: id,
        });
        if (interstitialAd) {
            interstitialAd.onClose(res => {
                // 插屏广告关闭事件  
                crtkc.err("插屏广告 onClose: ", res);
            })
            interstitialAd.onError(res => {
                // 插屏广告Error事件  
                crtkc.err("插屏广告 onError: ", res);
            })
            let p = interstitialAd.show()
            p.then(function (result) {
                // 插屏广告展示成功  
                console.error(`show interstitial ad success, result is ${result}`);
                this.nextInterTime = Date.now() + this.interGap;
            }).catch(function (error) {
                // 插屏广告展示失败  
                console.error('show interstitial ad failed, error is: ', error)
                if (error.code === -10005) {
                    // 表明当前app版本不支持插屏广告，可以提醒用户升级app版本 
                    console.error("不支持插屏广告");
                }
            })
        } else {
            console.log("创建插屏广告组件失败");
        }
    }


    showInter(isBanner: boolean = false, style?: any) {
        const id = this.getPara('insertAd');
        if (!id) {
            return;
        }
        // 插屏广告弹出页面
        // 0为关闭，1为开启
        if (!this.getCtrl('p4')) {
            return;
        }

        //原生插屏延迟
        const p5 = this.getCtrl('p5');
        const me = this;
        setTimeout(() => {
            me.doShowInter(isBanner, style);
        }, p5 * 1000);
    }



}